package twl.global.input;

import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;


import de.matthiasmann.twl.GUI;
import de.matthiasmann.twl.input.Input;

public class GlobalLwjglInput implements Input{
	
	private boolean wasActive;
	private GlobalGUI ggui;
	
	public GlobalLwjglInput(GlobalGUI ggui){
		this.ggui = ggui;
	}

	@Override
	public boolean pollInput(GUI gui) {
        boolean active = Display.isActive();
        if(wasActive && !active) {
            wasActive = false;
            return false;
        }
        wasActive = active;
        
        if(Keyboard.isCreated()) {
            while(Keyboard.next()) {
                gui.handleKey(
                        Keyboard.getEventKey(),
                        Keyboard.getEventCharacter(),
                        Keyboard.getEventKeyState());
                ggui.handleKey(
                        Keyboard.getEventKey(),
                        Keyboard.getEventCharacter(),
                        Keyboard.getEventKeyState());
            }
        }
        if(Mouse.isCreated()) {
            while(Mouse.next()) {
                gui.handleMouse(
                        Mouse.getEventX(), gui.getHeight() - Mouse.getEventY() - 1,
                        Mouse.getEventButton(), Mouse.getEventButtonState());
                ggui.handleMouse(
                        Mouse.getEventX(), gui.getHeight() - Mouse.getEventY() - 1,
                        Mouse.getEventButton(), Mouse.getEventButtonState());

                int wheelDelta = Mouse.getEventDWheel();
                if(wheelDelta != 0) {
                    gui.handleMouseWheel(wheelDelta / 120);
                    ggui.handleMouseWheel(wheelDelta / 120);
                }
            }
        }
        return true;
    }

}
